<template>
  <div class="app-container">
    <div v-if="setPermissionBtn('/server/role/query', searchBtn)" class="inputBox">
      <el-input v-model="search.name" class="input" placeholder="请输入角色名称查询" />
      <el-input v-model="search.createUser" class="input" placeholder="请输入创建人查询" />
      <el-date-picker
        v-model="search.startTime"
        class="startDate date"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="search.endTime"
        class="endDate date"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择结束日期"/>
      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
      <!-- <el-button v-show="permissionShow && permissionBoolean('新增')" type="primary" @click="addCourseType">新增</el-button> -->
      <!-- <el-button type="primary" @click="addCourseType">新增</el-button> -->
    </div>
    <el-button v-if="setPermissionBtn('/server/role/add', addBtn)" type="primary" class="addBtn" @click="toaddPage()">{{ addBtn.btnName }}</el-button><br><br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <el-table-column label="角色名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="角色描述">
        <template slot-scope="scope">
          <!-- {{ scope.row.role ? scope.row.role.name : '' }} -->
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="创建人">
        <template slot-scope="scope">
          {{ scope.row.createUser }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          <!-- {{ scope.row.userLoginRecord ? scope.row.userLoginRecord.loginTime : '' | formatDate }} -->
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="270">
        <template slot-scope="scope">
          <el-button
            v-if="setPermissionBtn('/server/role/query/info', scope.row)"
            v-show="permissionShow"
            value="查看"
            size="mini"
            type="warning"
            @click="dialogDetail(scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-show="permissionShow"
            size="mini"
            type="primary"
            @click="editRow(scope.$index)">编辑</el-button>
          <el-button
            v-show="permissionShow"
            size="mini"
            type="success"
            @click="permissionEditFn(scope.row.id)">权限设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <detail :detialvisible.sync="dialogTableVisible" :dialogdata.sync="list" :myindex.sync="detailIndex" :detail-mode="'sysRole'" />
  </div>
</template>

<script>
import { getSysUserList, editSysUser } from '@/api/sysUser'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import detail from '@/components/detail'
import { getRoleList } from '@/api/sysRole'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'

export default {
  components: { Pagination, detail },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeStr(type) {
      const typesMap = {
        0: '禁用',
        1: '启用'
      }
      return typesMap[type]
    }
  },
  data() {
    return {
      searchBtn: {},
      list: [],
      role: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      search: {
        name: '',
        createUser: '',
        startTime: '',
        endTime: ''
      },
      isShowDel: false,
      dialogFormVisible: false,
      temp: {
        status: ''
      },
      courseTypeId: null,
      course: {
        name: '',
        introduce: '',
        price: '',
        imgUrl: ''
      },

      isEdit: false,
      uploadData: {
        key: '',
        token: ''
      },
      dialogTableVisible: false,
      detailIndex: -1,
      permissionShow: true, // 权限数据未到达之前按钮隐藏
      permissionList: [], // 权限数据列表
      addBtn: {}
    }
  },
  computed: {
    startDate: function(e) {
      return new Date(this.startDate()).getTime()
    },
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    },
    // 用于 停用/启用  上架/下架 按钮的显示
    splitName() {
      return function(name, status) {
        console.log('name:', name)
        console.log('status:', status)
        const nameArr = name.split('/')
        if (status === 0) {
          return nameArr[0]
        } else {
          return nameArr[1]
        }
      }
    }
  },
  watch: {
    // 'permissionList'(newVal) {
    //   this.permissionList = newVal
    //   this.permissionShow = true
    // }
  },
  created() {
    this.fetchData()
    // 角色列表
    // getRoleList().then(response => {
    //   this.role = response.data.list
    //   console.log(this.role)
    // })
    // this.getPermissonFn()
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
  },
  methods: {
    toaddPage() {
      this.$router.push({
        path: '/basic/role/add'
      })
    },
    toReset() {
      this.search.name = ''
      this.search.createUser = ''
      this.search.startTime = ''
      this.search.endTime = ''
    },
    toSearch() {
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
      if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
      const newData = this.objectCon(this.listQuery, this.search)
      this.listLoading = true
      getRoleList(newData).then(response => {
        console.log('response:', response)
        if (response.code === '200') {
          this.list = response.data.list
          this.total = response.data.total
        } else {
          Message.error(response.message + '-' + response.data)
        }

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    fetchData() {
      const newData = this.objectCon(this.listQuery, this.search)
      this.listLoading = true
      getRoleList(newData).then(response => {
        console.log(response)
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    del(pid) {
      this.$confirm('确认要删除该咨询？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      }).catch(() => {
      })
    },
    dialogDetail(index) {
      this.dialogTableVisible = true
      this.detailIndex = index
    },
    edit(pid) {
      this.$router.push({
        path: '/vocational/courseAdd',
        query: {
          id: pid
        }
      })
    },
    addCourse(courseTypeId) {
      this.$data.courseTypeId = courseTypeId
      this.$data.dialogFormVisible = true
    },
    getValue(value) {
      this.$data.temp.status = value
    },
    getEnable(value) {
      this.$data.course.isEnable = value
    },
    getChildren(value) {
      this.$data.course.courseList = value
    },
    // addCourseType() {
    //   this.$router.push({
    //     path: '/basic/role/add',
    //     query: { isEdit: false }
    //   })
    // },
    editRow(pid) {
      const _this = this;
      const object = Object.assign({ isEdit: true }, _this.$data.list[pid])
      this.$router.push({
        path: '/basic/role/add',
        query: object
      })
    },
    permissionEditFn(rid) {
      const object = { rid }
      this.$router.push({
        path: '/basic/role/permissionEdit',
        query: object
      })
    }
  }
}
</script>

<style scoped>
  .el-icon-remove {
    margin-left: 10px;
  }
  .img_url {
    width: 110px;
    height: 110px;
  }

  .inputBox .input:nth-of-type(1){width:160px;}
  .inputBox .input:nth-of-type(2){width:160px;}
  .date{width:160px;}
</style>
